package com.wsz.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wsz.gateway.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    private static final Logger log = LoggerFactory.getLogger(AuthGlobalFilter.class);


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();


        log.info("path:{}",path);

        if(antPathMatcher.match("/codes/user/vc.jpg",path) || antPathMatcher.match("/codes/user/register",path)
        || antPathMatcher.match("/codes/user/login",path)  || antPathMatcher.match("/codes/user/token/refresh",path) || antPathMatcher.match("/websocket/**",path)
        || antPathMatcher.match("/codes/ucenter/login",path)){
            return chain.filter(exchange);
        }
        else {
            List<String> tokenList = request.getHeaders().get("AUTHORIZATION");
            if (null == tokenList) {
                return out(exchange.getResponse());
            } else {
                try{
                    DecodedJWT decodedJWT = null;
                    log.info("flag:{}",antPathMatcher.match("/codes/ucenter/**",path));
                    if(antPathMatcher.match("/codes/ucenter/**",path)) {
                        log.info("ucenter:{}",path);
                        decodedJWT = JwtUtils.parseAclToken(tokenList.get(0).substring("token:".length()));
                    }else{
                        decodedJWT = JwtUtils.parseToken(tokenList.get(0).substring("token:".length()));
                    }
                    if(decodedJWT == null){
                        return out(exchange.getResponse());
                    }
                }catch (Exception e){
                    return out(exchange.getResponse());
                }
            }
        }
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JSONObject message = new JSONObject();
        message.put("success", false);
        message.put("code", 201);
        message.put("message", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}